<?php
// +----------------------------------------------------------------------
// | NewThink [ Think More,Think Better! ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2018 http://www.newthink.cc All rights reserved.
// +----------------------------------------------------------------------
// | 版权所有：山西创泰网络科技有限公司
// +----------------------------------------------------------------------

namespace app\api\controller;

//use app\common\service\airquality\AirQualityService;
use MongoDB\BSON\ObjectId;
use think\Db;

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');

/**
 * 首页左侧切换面板的APIgetRealTimeIndex
 */
class IndexPanel extends BaseController
{
    // +----------------------------------------------------------------------
    // | 目录
    // | 注意：方法统一用英文，驼峰式
    // | L-1 空气站点概况
    // | L-2 实时指数
    // | L-3 排行
    // | L-4 六日预报
    // | L-5 48小时趋势图
    // +----------------------------------------------------------------------


    /**
     * L-1 空气站点概况
     *surface_temp,wind_dir,surface_wind,rh
     */
    public function airStationProfile()
    {
        $list = [];
        try {
            $sql  = 'select surface_temp, wind_dir, surface_wind, rh, sky_condition, sky_condition_icon
                    from air_quality_weather_realtime_hour 
                    where publish_time=(select max(replace(publish_time,\'/\',\'-\')) from air_quality_weather_realtime_hour )';
            $list = Db::query($sql)[0];

            $date         = date("Y/m/d");
            $weekarray    = array("周日", "周一", "周二", "周三", "周四", "周五", "周六");
            $list['week'] = $weekarray[date("w", strtotime($date))];

            if (empty($list)) {
                $this->error('获取空气站点概况数据失败!');
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success("空气站点概况查询成功", $list);
    }

    /**
     * L-2 实时指数
     * @author zhangjiangpeng 2019/03/21
     * @author lichao 2019/05/23
     * @edit dtt 2019/07/31 17:28 超标污染物站点id筛选
     */
    public function getRealTimeIndex()
    {
        $list = [];
        try {
            $sql = 'select  A.* , B.name as primaryName, C.name as attainmentName ';
            $sql .= 'from air_quality_station_aqi_realtime_hour as A ';
            $sql .= 'left join air_quality_station_primary_pollutant_realtime_hour B ';
            $sql .= 'on  A.publish_time = B.publish_time and B.station_id = 0 and B.region_id = 53 ';
            $sql .= 'left join air_quality_station_non_attainment_pollutant_realtime_hour C ';
            $sql .= 'on A.publish_time = C.publish_time  and C.station_id = 0 and B.station_id = 0 and B.region_id = 53 ';
            $sql .= 'where A.publish_time = (select max(replace(publish_time,\'/\',\'-\')) ';
            $sql .= 'from air_quality_station_aqi_realtime_hour) ';
            $sql .= 'and A.station_id = 0 and A.region_id = 53';

            $res = Db::query($sql);
            if (empty($res)) {
                $this->error('获取实时指数数据失败!');
            }
            $res               = $res[0];
            $list['aqi']       = $res['aqi'];
            $list['aqi_level'] = $res['aqi_level'];
            $list['aqi_color'] = $res['aqi_color'];

            $list['pm25']         = $res['pm25'];
            $list['pm25_level']   = $res['pm25_level'];
            $list['pm25_percent'] = $res['pm25_percent'];
            $list['pm25_color']   = $res['pm25_color'];

            $list['pm10']         = $res['pm10'];
            $list['pm10_level']   = $res['pm10_level'];
            $list['pm10_percent'] = $res['pm10_percent'];
            $list['pm10_color']   = $res['pm10_color'];

            $list['so2']         = $res['so2'];
            $list['so2_level']   = $res['so2_level'];
            $list['so2_percent'] = $res['so2_percent'];
            $list['so2_color']   = $res['so2_color'];

            $list['no2']         = $res['no2'];
            $list['no2_level']   = $res['no2_level'];
            $list['no2_percent'] = $res['no2_percent'];
            $list['no2_color']   = $res['no2_color'];

            $list['o3']         = $res['o3'];
            $list['o3_level']   = $res['o3_level'];
            $list['o3_percent'] = $res['o3_percent'];
            $list['o3_color']   = $res['o3_color'];

            $list['co']         = $res['co'];
            $list['co_level']   = $res['co_level'];
            $list['co_percent'] = $res['co_percent'];
            $list['co_color']   = $res['co_color'];
            //发布时间
            $list['publish_time'] = date("m/d G:i", strtotime($res['publish_time']));
            // 首要污染物
            if (!empty($res['primaryName'])) {
                $list['primaryName'] = strtoupper($res['primaryName']) == 'PM25' ? 'PM2.5' : strtoupper($res['primaryName']);
            } else {
                $list['primaryName'] = '-';
            }

            // 超标污染物
            if (!empty($res['attainmentName'])) {
                $attainmentName = strtoupper($res['attainmentName']) == 'PM25' ? 'PM2.5' : strtoupper($res['attainmentName']);
            } else {
                $attainmentName = '-';
            }

            $list['attainmentName'] = $attainmentName;

            if (empty($list)) {
                $this->error('获取实时指数数据失败!');
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success("实时指数查询成功", $list);
    }

    /**
     * L-3 排行
     * @author zhangjiangpeng 2019/03/21
     * country_aqi_rank,country_percent,28city_aqi_rank,province_aqi_rank
     */
    public function getCityRanking()
    {
        $list = [];
        try {
            $sql               = 'select country_aqi_rank,country_percent,28city_aqi_rank,province_aqi_rank
                    from air_quality_aqi_city_rank
                    where publish_time = (select max(replace(publish_time,\'/\',\'-\')) from air_quality_aqi_city_rank)';
            $list              = Db::query($sql)[0];
            $list['beat_city'] = round(100 - floatval($list['country_percent']), 2) . '%';

            unset($list['country_percent']);

            if (empty($list)) {
                $this->error('获取排行数据失败!');
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }


        $this->success("排行查询成功", $list);
    }

    /**
     * 获取指定日期段内每一天的日期
     * @param Date $startdate 开始日期
     * @param Date $enddate 结束日期
     * @return Array
     */
    function getDateFromRange($startdate, $enddate, $hour = false)
    {
        $stimestamp = strtotime($startdate);
        $etimestamp = strtotime($enddate);
        // 计算日期段内有多少天
        if ($hour) {
            $days = ($etimestamp - $stimestamp) / 3600 + 1;
            // 保存每天日期
            $date = array();
            for ($i = 0; $i < $days; $i++) {
                $date[] = date('H:i', $stimestamp + (3600 * $i));
            }
        } else {
            $days = ($etimestamp - $stimestamp) / 86400 + 1;
            // 保存每天日期
            $date = array();
            for ($i = 0; $i < $days; $i++) {
                $date[] = date('m/d', $stimestamp + (86400 * $i));
            }
        }

        return $date;
    }

    /**
     * L-4 六日预报
     * @author zhangjiangpeng 2019/03/21
     * @author lichao 2019/05/13
     * predict_time,maximum_temperature,minimum_temperature,average_cloud_cover,average_wind
     * 注：aqi查询站点station_id为0的数据，后期需要计算插入station_id为0的数据
     */
    public function get6DayForecast()
    {
        $list = [];
        try {
            $time = strtotime(date('Y-m-d 08:05:00'));
            // 如果当前时间小于8点40，则取天气表和站点表前一天的数据
            if (time() < $time) {
                $currentTime        = date('Y-m-d 00:00:00');
                $weatherPublishTime = date('Y-m-d 00:00:00', strtotime("-1 day"));
                $stationPublishTime = date('Y-m-d 00:00:00', strtotime("-1 day"));
            } else {
                $currentTime        = date('Y-m-d 00:00:00', strtotime("+1 day"));
                $weatherPublishTime = date('Y-m-d 00:00:00');
                $stationPublishTime = date('Y-m-d 00:00:00');
            }
            $sixDay = date('Y-m-d 00:00:00', strtotime($currentTime) + 5 * 24 * 3600);

            $todayYearWeek = $this->getDateFromRange($currentTime, $sixDay);
            foreach ($todayYearWeek as $index => $value) {
                $list[$index]['publish_time']        = date("m/d H:i", strtotime($weatherPublishTime));
                $list[$index]['predict_time']        = date("m/d", strtotime($value));
                $list[$index]['maximum_temperature'] = '';
                $list[$index]['minimum_temperature'] = '';
                $list[$index]['weather']['name']     = '';
                $list[$index]['weather']['icon']     = '';
                $list[$index]['highest_wind']        = '';
                $list[$index]['minimum_wind']        = '';
                $list[$index]['aqi']                 = '';
                $list[$index]['aqi_level']           = '';
            }

            // 获取天气预测值
            $weatherForecastSql = "SELECT * FROM `air_quality_weather_forecast_day` WHERE `region_id` = 53 AND 
`predict_time` between ? AND ? AND `publish_time` = ?";
            $res                = Db::query($weatherForecastSql, array($currentTime, $sixDay, $weatherPublishTime));

            // 获取站点预测值
            $stationForecastSql = "SELECT * FROM `air_quality_station_aqi_forecast_day` WHERE `region_id` = 53 AND 
`station_id` = ? AND `predict_time` between ? AND ? AND `publish_time` = ?";
            $res2               = Db::query($stationForecastSql, array(0, $currentTime, $sixDay, $stationPublishTime));

            foreach ($res as $k => &$v) {
                foreach ($res2 as $key => $item) {
                    if ($v['predict_time'] == $item['predict_time']) {
                        $list[$k]['maximum_temperature'] = $v['maximum_temperature'];
                        $list[$k]['minimum_temperature'] = $v['minimum_temperature'];
                        $list[$k]['weather']['name']     = $v['minimum_sky_condition'];
                        $list[$k]['weather']['icon']     = $v['minimum_sky_condition_icon'];
                        $list[$k]['highest_wind']        = $v['highest_wind'];
                        $list[$k]['minimum_wind']        = $v['minimum_wind'];
                        $list[$k]['aqi']                 = round($item['aqi']);
                        $list[$k]['aqi_level']           = $item['aqi_level'];
                    }
                }
            }

            if (empty($list)) {
                $this->error('六日预报查询失败!');
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success("六日预报查询成功", $list);
    }


    /**
     * L-5 48小时趋势图
     * @author zhangjiangpeng 2019/03/21
     * @author lichao 2019/05/13
     */
    public function getTendencyChart()
    {
        $list = [];
        try {
            $date      = date("Y-m-d 00:00:00");                                // 发布时间为当前时间
            $startTime = date("Y-m-d H:00:00");                                 // 预测开始时间
            $endTime   = date("Y-m-d H:00:00", strtotime($startTime) + 47 * 3600);     //预测结束时间
            $sql       = 'select predict_time,aqi from air_quality_station_aqi_forecast_hour where region_id = 53 AND publish_time = ? AND predict_time BETWEEN ? AND ? order by id asc limit 48';
            $result    = Db::query($sql, array($date, $startTime, $endTime));
            // $result = array_reverse($result);
            $todayYearWeek = $this->getDateFromRange($startTime, $endTime, true);

            foreach ($todayYearWeek as $key => $value) {
                $list['date'][$key] = $value;
                $list['data'][$key] = null;
            }

            foreach ($result as $k => $v) {
                // $list['date'][$k] = date("H:i", strtotime($v['predict_time']));
                $list['data'][$k] = $v['aqi'];
            }

            if (empty($list)) {
                $this->error('获取48小时趋势图数据失败!');
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success("48小时趋势图查询成功", $list);
    }
}


